package yf.mall.service.impl;

import org.apache.catalina.User;
import yf.mall.dao.AccountDao;
import yf.mall.dao.LevelRecordDao;
import yf.mall.dao.UserDao;
import yf.mall.entity.LevelRecordEntity;
import yf.mall.entity.UserEntity;
import com.yf.service.impl.BaseServiceImpl;
import yf.mall.enums.LevelAuthEnum;
import yf.mall.enums.LevelTypeEnum;
import com.yf.response.RRException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import yf.mall.dao.LevelDao;
import yf.mall.entity.LevelEntity;
import yf.mall.service.LevelService;
import org.springframework.transaction.annotation.Transactional;
import yf.mall.service.UserService;

/**
 * 级别Service实现类
 *
 * @author hxf
 * @email 505860922@qq.com
 * @date Thu Jul 11 12:00:51 CST 2019
 */
@Service
public class LevelServiceImpl extends BaseServiceImpl<LevelEntity> implements LevelService {

    private LevelDao levelDao;

    @Autowired
    private AccountDao accountDao;


    @Autowired
    public void setDao(LevelDao levelDao) {
        this.levelDao = levelDao;
        super.setBaseDao(levelDao);
    }


    /**内部方法**/


    /**
     * 外部方法实现
     **/

    @Override
    public List<LevelEntity> findLowLevel(Long userId) {
        List<LevelEntity> levelEntities = levelDao.queryList(null);
        UserEntity userEntity = userDao.get(userId);
        LevelEntity levelEntity = levelDao.get(userEntity.getLevelId());
        if (levelEntity.getLv() < 45){
            levelEntities = levelEntities.stream().filter(level ->
                    level.getLv() >= levelEntity.getLv() && level.getType().equals(LevelTypeEnum.PUB.getIndex())
            ).collect(Collectors.toList());
        }else {
            levelEntities = levelEntities.stream().filter(level ->
                    level.getLv() > levelEntity.getLv() && level.getType().equals(LevelTypeEnum.PUB.getIndex())
            ).collect(Collectors.toList());
        }
        return levelEntities;
    }

    @Autowired
    private UserService userService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LevelEntity changeLevel(Long userId, Long toUserId, Long levelId) {
        UserEntity userEntity = userDao.get(userId);
        UserEntity toUser = userDao.get(toUserId);
        if (!toUser.getPid().equals(userEntity.getId())) {
            throw new RRException("无权限操作!");
        }
        //不可以操作内部级别用户
        if (levelDao.get(toUser.getLevelId()).getType().equals(LevelTypeEnum.PRI.getIndex())) {
            throw new RRException("无权限对此级别用户操作!");
        }
        LevelEntity toLevel = levelDao.get(levelId);
        if (!toLevel.getType().equals(LevelTypeEnum.PUB.getIndex())) {
            throw new RRException("非法操作级别");
        }
//        this.userService.updateExp(toUserId, toLevel);
        LevelEntity level = levelDao.get(userEntity.getLevelId());
        //大区以上不允许升级同等级以上的级别
        if (level.getLv() <= 5){
            if (level.getLv() >= toLevel.getLv()) {
                throw new RRException("非法操作级别!");
            }
        }else {
            if (level.getLv() > toLevel.getLv()) {
                throw new RRException("非法操作级别!");
            }
        }
        toUser.setLevelId(levelId);

        userDao.update(toUser);
        return toLevel;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<LevelEntity> findlist() {
        List<LevelEntity> levelList = this.levelDao.findLevelList();
        return levelList;
    }

    @Autowired
    private LevelRecordDao levelRecordDao;

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public LevelEntity changeLevelByExp(Long userId, BigDecimal exp) {
//        //比较当前人的经验值跟自己的级别是否同步 如果比自己的级别该有的少 则补上
//        LevelEntity levelEntity = levelDao.findByUserId(userId);
//        LevelEntity temLv = findByExp(exp);
//        UserEntity userEntity = userDao.get(userId);
//        if (temLv.getType() == LevelTypeEnum.PUB.getIndex()) {
//            //需要升级
//            userEntity.setLevelId(temLv.getId());
//        } else {
//            LevelEntity max = levelDao.findBaseMax();
//            //如果要往高等级别升 且本身级别比最低级别低  只能升级到最低可升级级别
//            if (levelEntity.getLv() > max.getLv()) {
//                //设置成最高可以升级级别
//                userEntity.setLevelId(max.getId());
//            }
//        }
//        LevelEntity toLv = levelDao.get(userEntity.getLevelId());
//        if (!levelEntity.getLv().equals(toLv.getLv())) {
//            LevelRecordEntity lvRecord = new LevelRecordEntity();
//            lvRecord.setUserId(userEntity.getId());
//            lvRecord.setNowLevel(toLv.getName());
//            lvRecord.setOldLevel(levelEntity.getName());
//            lvRecord.setTime(new Date());
//            levelRecordDao.save(lvRecord);
//        }
//        userDao.update(userEntity);
//        return levelEntity;
//    }

//    @Override
//    public LevelEntity findByUserId(Long userId,String auth) {
//        return levelDao.findByUserId(userId);
//    }


    @Override
    public LevelEntity findByUserId(Long userId, String auth) {
       String[] levels = initBaseLevel(userId);
        return levelDao.findByNameAndAuth(levels[LevelAuthEnum.indexOf(auth)],auth);
    }

   public String[] initBaseLevel(Long userId){
       UserEntity user = userDao.get(userId);
       String[] lvs = new String[0];
       if(user.getLevel()!=null){
           lvs  = user.getLevel().split("_");
       }
       //不存在级别 创建级别
       String[] levels = new String[LevelAuthEnum.names().length];
       //级别设置正常
       if(lvs.length==LevelAuthEnum.names().length){
           levels = lvs;
       }else {//不正常设置最低级别
           for (int i = 0; i < LevelAuthEnum.names().length; i++) {
               if(i<lvs.length){//原来的
                   levels[i] = lvs[i];
               }else {//赋值最小的
                   levels[i] = levelDao.findBase(LevelAuthEnum.names()[i]).getName();
               }
           }
           user.setLevel(Arrays.stream(levels).collect(Collectors.joining("_")));
           userDao.update(user);
       }
       return levels;
   }



//    @Override
//    public LevelEntity findByExp(BigDecimal exp) {
//        LevelEntity levelEntity = levelDao.findBase();
//        List<LevelEntity> levelEntities = levelDao.findLevelList();
//        for (LevelEntity level : levelEntities) {
//            if (exp.compareTo(level.getAmount()) >= 0) {
//                levelEntity = level;
//            }
//        }
//        return levelEntity;
//    }

    @Autowired
    private UserDao userDao;
}
